package utils

import (
	"math/rand"
	"net/url"
	"regexp"
	"time"
	"unsafe"
)

var NumericCharacter = "0123456789"
var LowercaseCharacter = "abcdefghijklmnopqrstuvwxyz"
var UppercaseCharacter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var AllRunes = NumericCharacter + LowercaseCharacter + UppercaseCharacter

const (
	letterIdxBits = 6                    // 6 bits to represent a letter index
	letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
	letterIdxMax  = 63 / letterIdxBits   // # of letter indices fitting in 63 bits
)

func RandString(n, charType int, extStr string) string {
	b := make([]byte, n)
	randSrc := rand.NewSource(time.Now().UnixNano())
	var letters string
	// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
	switch {
	case charType == 1:
		letters = NumericCharacter
	case charType == 2:
		letters = LowercaseCharacter
	case charType == 3:
		letters = UppercaseCharacter
	case charType == 4:
		letters = NumericCharacter + LowercaseCharacter
	case charType == 5:
		letters = NumericCharacter + UppercaseCharacter
	case charType == 6:
		letters = LowercaseCharacter + UppercaseCharacter
	}
	if letters == "" {
		letters = AllRunes
	}
	if extStr != "" {
		letters += extStr
	}
	for i, cache, remain := n-1, randSrc.Int63(), letterIdxMax; i >= 0; {
		if remain == 0 {
			cache, remain = randSrc.Int63(), letterIdxMax
		}
		if idx := int(cache & letterIdxMask); idx < len(letters) {
			b[i] = letters[idx]
			i--
		}
		cache >>= letterIdxBits
		remain--
	}
	return *(*string)(unsafe.Pointer(&b))
}

func IsURL(str string) bool {
	parsedURL, err := url.Parse(str)
	if err != nil || parsedURL.Scheme == "" || parsedURL.Host == "" {
		return false
	}
	return true
}

func FixPossibleURL(str string) string {
	urlRegex := regexp.MustCompile(`^\S+\.[^\s/]{1,6}/*\S*$`)
	is := urlRegex.MatchString(str)
	fixedUrl := ""
	if is {
		fixedUrl = `https://` + str
	}
	return fixedUrl
}
